<template>
  <div class="min-h-screen bg-gradient-to-br from-blue-50 to-indigo-100 py-[30px] px-[15px]">
    <div class="w-full bg-white rounded-lg shadow-md p-6">
      <div class="mb-6">
        <h1 class="text-2xl font-bold text-gray-800 no-select mb-4">文本转换</h1>
        <div class="flex justify-between items-center">
          <button 
            @click="toggleHistoryPanel" 
            class="px-3 py-1 bg-gray-600 text-white rounded-md hover:bg-gray-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-gray-500 flex items-center no-select"
          >
            <svg xmlns="http://www.w3.org/2000/svg" class="h-4 w-4 mr-1" viewBox="0 0 20 20" fill="currentColor">
              <path fill-rule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zm1-12a1 1 0 10-2 0v4a1 1 0 00.293.707l2.828 2.829a1 1 0 101.415-1.415L11 9.586V6z" clip-rule="evenodd" />
            </svg>
            历史记录
          </button>
          <button 
            @click="toggleMarkdownMode" 
            class="px-3 py-1 bg-blue-600 text-white rounded-md hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500 no-select"
          >
            {{ isMarkdownMode ? '普通文本' : 'markdown' }}
          </button>
        </div>
      </div>
      
      <div class="flex flex-col md:flex-row gap-6">
        <!-- 左侧：输入文本和转换选项 -->
        <div class="w-full md:w-1/2">
          <div class="mb-6">
            <label class="block text-sm font-medium text-gray-700 mb-2 no-select">输入文本</label>
            <!-- Markdown编辑器 -->
            <div v-if="isMarkdownMode" class="border border-gray-300 rounded-md overflow-hidden">
              <MdEditor
                v-model="inputText"
                :preview="true"
                :toolbarsExclude="['github', 'save']"
                previewTheme="github"
                style="height: 620px"
                :language="language"
              />
            </div>
            <!-- 普通文本框 -->
            <textarea 
              v-else
              v-model="inputText" 
              class="w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-indigo-500 focus:border-indigo-500" 
              rows="25"
              placeholder="请粘贴或输入需要转换的文本..."
            ></textarea>
          </div>
          
          <div class="mb-6">
            <label class="block text-sm font-medium text-gray-700 mb-2 no-select">转换选项</label>
            <div class="grid grid-cols-1 md:grid-cols-2 gap-2">
              <div class="flex items-center">
                <input 
                  type="checkbox" 
                  id="toUpperCase" 
                  v-model="options.toUpperCase" 
                  class="h-4 w-4 text-indigo-600 focus:ring-indigo-500 border-gray-300 rounded"
                />
                <label for="toUpperCase" class="ml-2 block text-sm text-gray-700 no-select">转换为大写</label>
              </div>
              <div class="flex items-center">
                <input 
                  type="checkbox" 
                  id="toLowerCase" 
                  v-model="options.toLowerCase" 
                  class="h-4 w-4 text-indigo-600 focus:ring-indigo-500 border-gray-300 rounded"
                />
                <label for="toLowerCase" class="ml-2 block text-sm text-gray-700 no-select">转换为小写</label>
              </div>
              <div class="flex items-center">
                <input 
                  type="checkbox" 
                  id="trimSpaces" 
                  v-model="options.trimSpaces" 
                  class="h-4 w-4 text-indigo-600 focus:ring-indigo-500 border-gray-300 rounded"
                />
                <label for="trimSpaces" class="ml-2 block text-sm text-gray-700 no-select">去除空格</label>
              </div>
              <div class="flex items-center">
                <input 
                  type="checkbox" 
                  id="removeNewlines" 
                  v-model="options.removeNewlines" 
                  class="h-4 w-4 text-indigo-600 focus:ring-indigo-500 border-gray-300 rounded"
                />
                <label for="removeNewlines" class="ml-2 block text-sm text-gray-700 no-select">去除换行符</label>
              </div>
              <div class="flex items-center">
                <input 
                  type="checkbox" 
                  id="reverseText" 
                  v-model="options.reverseText" 
                  class="h-4 w-4 text-indigo-600 focus:ring-indigo-500 border-gray-300 rounded"
                />
                <label for="reverseText" class="ml-2 block text-sm text-gray-700 no-select">反转文本</label>
              </div>
              <div class="flex items-center">
                <input 
                  type="checkbox" 
                  id="camelCase" 
                  v-model="options.camelCase" 
                  class="h-4 w-4 text-indigo-600 focus:ring-indigo-500 border-gray-300 rounded"
                />
                <label for="camelCase" class="ml-2 block text-sm text-gray-700 no-select">驼峰命名</label>
              </div>
              <div class="flex items-center">
                <input 
                  type="checkbox" 
                  id="fishDoc" 
                  v-model="options.fishDoc" 
                  class="h-4 w-4 text-indigo-600 focus:ring-indigo-500 border-gray-300 rounded"
                />
                <label for="fishDoc" class="ml-2 block text-sm text-gray-700 no-select">wolai格式</label>
              </div>
            </div>
            
            <div class="mt-4 space-y-4">
              <div>
                <label for="addPrefix" class="block text-sm font-medium text-gray-700 mb-1 no-select">添加前缀</label>
                <input 
                  type="text" 
                  id="addPrefix" 
                  v-model="options.prefix" 
                  class="w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-indigo-500 focus:border-indigo-500"
                  placeholder="输入要添加的前缀..."
                />
              </div>
              <div>
                <label for="addSuffix" class="block text-sm font-medium text-gray-700 mb-1 no-select">添加后缀</label>
                <input 
                  type="text" 
                  id="addSuffix" 
                  v-model="options.suffix" 
                  class="w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-indigo-500 focus:border-indigo-500"
                  placeholder="输入要添加的后缀..."
                />
              </div>
            </div>
          </div>
        </div>
        
        <!-- 右侧：转换结果和按钮 -->
        <div class="w-full md:w-1/2">
          <div class="mb-6">
            <label class="block text-sm font-medium text-gray-700 mb-2 no-select">转换结果</label>
            <!-- Markdown编辑器 -->
            <div v-if="isMarkdownMode" class="border border-gray-300 rounded-md overflow-hidden">
              <MdEditor
                v-model="outputText"
                :preview="true"
                :toolbarsExclude="['github', 'save']"
                previewTheme="github"
                style="height: 620px"
                :language="language"
                :editable="false"
              />
            </div>
            <!-- 普通文本框 -->
            <textarea 
              v-else
              v-model="outputText" 
              class="w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-indigo-500 focus:border-indigo-500" 
              rows="25"
              readonly
            ></textarea>
          </div>
          
          <div class="flex justify-between items-center">
            <div v-if="copyMessage" class="text-sm" :class="copyMessage.includes('失败') ? 'text-red-500' : 'text-green-500'">
              {{ copyMessage }}
            </div>
            <div class="flex flex-wrap gap-2">
              <button 
                @click="clearInput" 
                class="px-4 py-2 bg-red-600 text-white rounded-md hover:bg-red-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-red-500 no-select whitespace-nowrap"
              >
                清空输入
              </button>
              <button 
                @click="convertText" 
                class="px-4 py-2 bg-indigo-600 text-white rounded-md hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500 no-select whitespace-nowrap"
              >
                转换文本
              </button>
              <button 
                @click="copyToClipboard" 
                class="px-4 py-2 bg-green-600 text-white rounded-md hover:bg-green-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-green-500 no-select whitespace-nowrap"
                :disabled="!outputText"
              >
                复制结果
              </button>
            </div>
          </div>
        </div>
      </div>
    </div>
    <!-- 历史记录面板 -->
    <HistoryPanel 
      :records="historyRecords" 
      :isOpen="isHistoryPanelOpen"
      @close="toggleHistoryPanel"
      @select="selectHistoryRecord"
      @clear="clearHistory"
    />
  </div>
</template>

<script setup>
import { ref, watch, onMounted } from 'vue';
import HistoryPanel from '../components/HistoryPanel.vue';
import { app } from '../utils/cloudbase';

const inputText = ref('');
const outputText = ref('');
const copyMessage = ref('');
const isMarkdownMode = ref(false);
const showMarkdownSource = ref(false);
const isHistoryPanelOpen = ref(false);
const historyRecords = ref([]);
const language = ref('zh-CN');
const options = ref({
  toUpperCase: false,
  toLowerCase: false,
  trimSpaces: false,
  removeNewlines: false,
  reverseText: false,
  camelCase: false,
  fishDoc: false,
  prefix: '',
  suffix: ''
});

// 加载历史记录
const loadHistory = async () => {
  try {
    const historyJson = localStorage.getItem('textConverterHistory');
    if (historyJson) {
      historyRecords.value = JSON.parse(historyJson);
    }
  } catch (error) {
    console.error('加载历史记录失败:', error);
  }
};

// 保存历史记录
const saveHistory = () => {
  try {
    localStorage.setItem('textConverterHistory', JSON.stringify(historyRecords.value));
  } catch (error) {
    console.error('保存历史记录失败:', error);
  }
};

// 清空历史记录
const clearHistory = () => {
  historyRecords.value = [];
  saveHistory();
};

// 选择历史记录
const selectHistoryRecord = (record) => {
  inputText.value = record.input;
  outputText.value = record.output;
  
  // 复制选项
  Object.keys(options.value).forEach(key => {
    if (record.options[key] !== undefined) {
      options.value[key] = record.options[key];
    }
  });
  
  // 关闭历史面板
  isHistoryPanelOpen.value = false;
};

// 切换历史面板
const toggleHistoryPanel = () => {
  isHistoryPanelOpen.value = !isHistoryPanelOpen.value;
};

// 在组件挂载时加载历史记录
onMounted(() => {
  loadHistory();
});

const convertText = () => {
  // 检查是否选择了任何转换选项或输入了前缀/后缀
  const hasOptions = options.value.toUpperCase || 
                    options.value.toLowerCase || 
                    options.value.trimSpaces || 
                    options.value.removeNewlines || 
                    options.value.reverseText || 
                    options.value.camelCase || 
                    options.value.fishDoc || 
                    options.value.prefix || 
                    options.value.suffix;
  
  if (!hasOptions) {
    // 使用DaisyUI的toast提示替代原生alert
    const toast = document.createElement('div');
    toast.className = 'toast toast-top toast-center';
    toast.innerHTML = `
      <div class="alert alert-warning">
        <svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6 shrink-0 stroke-current" fill="none" viewBox="0 0 24 24">
          <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z" />
        </svg>
        <span>请先输入文本并填写需要的转换功能</span>
      </div>
    `;
    document.body.appendChild(toast);
    
    // 3秒后自动移除提示
    setTimeout(() => {
      document.body.removeChild(toast);
    }, 3000);
    
    return;
  }
  
  let result = inputText.value;
  
  // 应用前缀
  if (options.value.prefix) {
    result = options.value.prefix + result;
  }
  
  // wolai格式转换
  if (options.value.fishDoc) {
    // 匹配 "▼\n语言名\n复制代码" 格式，转换为 ```语言名
    // result = result.replace(/▼\s*\n([a-zA-Z0-9]+)\s*\n复制代码/g, '```$1');
    result = result.replace(/▼\s*([a-zA-Z0-9]+)\s*复制代码/g, '')
            // 遇到 `![img]`  和`![image]` 和 `![null]`替换为 `![]`
            .replace(/!\[img\]/g, '![]')
            .replace(/!\[image\]/g, '![]')
            .replace(/!\[null\]/g, '![]')
            // 遇到 `![](![]` 替换为 `![]`
            .replace(/!\[\]\(!\[\]/g, '![]')
            // 遇到base64编码替换为 "" ={1,2}表示=出现1到2次 前4位全为数字则保留前4位，否则全删除
            .replace(/[a-zA-Z0-9+\/]{20,}={1,2}/g, (match) => {
              // 检查前4位是否全为数字
              if (/^\d{4}/.test(match)) {
                return match.slice(0, 4); // 保留前4位
              }
              return ''; // 否则全部删除
            })
            // 遇到多个横线转换成三个横线
            .replace(/-{3,}/g, '---')


  }
  
  // 大小写转换
  if (options.value.toUpperCase) {
    result = result.toUpperCase();
  }
  
  if (options.value.toLowerCase) {
    result = result.toLowerCase();
  }
  
  // 空格和换行处理
  if (options.value.trimSpaces) {
    result = result.replace(/\s+/g, '');
  } else if (options.value.removeNewlines) {
    result = result.replace(/\n/g, ' ');
  }
  
  // 文本反转
  if (options.value.reverseText) {
    result = result.split('').reverse().join('');
  }
  
  // 驼峰命名转换
  if (options.value.camelCase) {
    result = result
      .replace(/[\s-_]+(.)/g, (_, c) => c.toUpperCase())
      .replace(/^(.)/, (_, c) => c.toLowerCase());
  }
  
  // 应用后缀
  if (options.value.suffix) {
    result = result + options.value.suffix;
  }
  
  outputText.value = result;
  
  // 保存到历史记录
  if (inputText.value && result) {
    const historyRecord = {
      input: inputText.value,
      output: result,
      options: { ...options.value },
      timestamp: new Date().getTime()
    };
    
    // 添加到历史记录开头
    historyRecords.value.unshift(historyRecord);
    
    // 限制历史记录数量，最多保存20条
    if (historyRecords.value.length > 20) {
      historyRecords.value = historyRecords.value.slice(0, 20);
    }
    
    // 保存到本地存储
    saveHistory();
  }
};

const copyToClipboard = async () => {
  try {
    await navigator.clipboard.writeText(outputText.value);
    copyMessage.value = '已复制到剪贴板！';
    setTimeout(() => {
      copyMessage.value = '';
    }, 2000);
  } catch (error) {
    console.error('复制失败:', error);
    copyMessage.value = '复制失败，请重试！';
    setTimeout(() => {
      copyMessage.value = '';
    }, 2000);
  }
};

// 仅在输入文本为空时清空输出文本，不再自动转换
watch(inputText, (newValue) => {
  if (!newValue) {
    outputText.value = '';
  }
});

const toggleMarkdownMode = () => {
  isMarkdownMode.value = !isMarkdownMode.value;
  // 重置源代码显示状态
  if (!isMarkdownMode.value) {
    showMarkdownSource.value = false;
  }
};

// 清空输入框
const clearInput = () => {
  inputText.value = '';
  outputText.value = '';
};

// 监听大小写选项，实现互斥功能
watch(() => options.value.toUpperCase, (newValue) => {
  if (newValue) {
    options.value.toLowerCase = false;
  }
});

watch(() => options.value.toLowerCase, (newValue) => {
  if (newValue) {
    options.value.toUpperCase = false;
  }
});


</script>